"use client";
import React, { useEffect, useState } from "react";
import {
  Tabs,
  Input,
  Select,
  Form,
  Button,
  Table,
  Space,
  Modal,
  Popconfirm,
  Drawer
} from "antd";
import {
  SearchOutlined,
  RedoOutlined,
  HourglassOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import type { TableColumnsType, TableProps } from "antd";
import Modals from "@/app/[locale]/hbs/modal";
import axios from "axios";
import dayjs from "dayjs";
type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];
interface DataType {
  id: number;
  name: string;
  khzt: string;
  khxj: number;
  lxr: string;
  phone: number;
  time: number;
  timefalse: number;
}
const onChange: TableProps<DataType>["onChange"] = (
  pagination,
  filters,
  sorter,
  extra
) => {
  console.log("params", pagination, filters, sorter, extra);
};

export default function Lsy() {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        id: "odd",
        text: "Select Odd Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };
  const columns: TableColumnsType<DataType> = [
    {
      title: "商机标题",
      dataIndex: "khzt",
      width: 130,
      render: (khzt, record) => <a>{khzt}</a>,
    },
    {
      title: "关联客户",
      dataIndex: "name",
      width: 220,
      render: (name, record) => <a>{name}</a>,
    },
    {
      title: "商机阶段",
      dataIndex: "khxj",
      width: 150,
      sorter: {
        compare: (a, b) => a.khxj - b.khxj,
        multiple: 2,
      },
      showSorterTooltip: false,
    },
    {
      title: "报价记录",
      dataIndex: "lxr",
      width: 120,
      render: (lxr, record) => <a>{lxr}</a>,
    },
    {
      title: "报价总金额",
      dataIndex: "phone",
      width: 150,
      sorter: {
        compare: (a, b) => a.phone - b.phone,
        multiple: 1,
      },
      showSorterTooltip: false,
    },
    {
      title: "最后跟进",
      dataIndex: "time",
      width: 150,
      sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 1,
      },
      render: (data) => {
        return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
      },
      showSorterTooltip: false,
    },
    {
      title: "未跟进天数",
      dataIndex: "timefalse",
      width: 120,
      align: "center",
      sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 1,
      },
      showSorterTooltip: false,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <a>更进</a>
          <a
            onClick={() => {
              setTitle("编辑");
              showModal();
              setObjItem(record);
            }}
          >
            编辑
          </a>
          <a
            onClick={() => {
              let index = data.findIndex((item) => item.id == record.id);
              console.log(index, "/置顶的下标");

              data.splice(index, 1);
              // data.unshift(record);
              console.log(data, "/置顶后的数组");
              setDate([record, ...data]);
            }}
          >
            置顶
          </a>
          <Popconfirm
            title="删除提示"
            description="是否确定删除?"
            onConfirm={async () => {
              await axios.delete(`http://localhost:3000/data/${record.id}`, {
                headers: { "Content-Type": "application/json" },
              });
              getDate();
            }}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [data, setDate] = useState([]);
  // 获取所有数据
  const getDate = async () => {
    let res = await axios
      .get("http://localhost:3000/data")
      .then((res) => res.data);
    setDate(res);
  };
  useEffect(() => {
    getDate();
  }, []);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title, setTitle] = useState("添加");
  const [objItem, setObjItem] = useState({});
  const showModal = () => {
    setIsModalOpen(true);
  };
  // 编辑数据
  const handleOk = async (obj: any) => {
    setIsModalOpen(false);
    await axios.patch(`http://localhost:3000/data/${obj.id}`, obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };
  // 添加数据
  const handleCancel = async (obj: any) => {
    setIsModalOpen(false);
    await axios.post("http://localhost:3000/data", obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };
  const [keyword, setKeyword] = useState("");
  const [customerStatus, setCustomerStatus] = useState("");
  const [customerType, setCustomerType] = useState("");
  const [lastFollowUp, setLastFollowUp] = useState("");
  // 搜索事件
  const handleSearch = async () => {
    try {
      const response = await axios.get("http://localhost:3000/data", {
        params: {
          khzt_like: keyword != "" ? keyword : undefined,
          khxj: customerStatus != "" ? customerStatus : undefined,
          name: customerType != "" ? customerType : undefined,
          time: lastFollowUp != "" ? lastFollowUp : undefined,
        },
      });
      setDate(response.data);
      console.log(keyword);
    } catch (error) {
      console.error("搜索出错:", error);
    }
  };
  let [form] = Form.useForm();
    //抽屉
    const [open, setOpen] = useState(false);
    const showDrawer = () => {
      setOpen(true);
    };
    const onClose = () => {
      setOpen(false);
    };
  return (
    <div
      style={{
        width: "100%",
        height: "725px",
        backgroundImage: "none",
        textAlign: "left",
        overflow: "auto",
      }}
    >
      {/* 头部tab标签 */}
      <div
        style={{
          display: "flex",
          height: "50px",
          width: "800px",
          justifyContent: "left",
        }}
      >
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              label: "全部客户",
              key: "1",
            },
            {
              label: "我的客户",
              key: "2",
            },
            {
              label: "下属客户",
              key: "3",
            },
            {
              label: "重点客户",
              key: "4",
            },
            {
              label: "我协作的",
              key: "5",
            },
            {
              label: "下属协作的",
              key: "6",
            },
          ]}
        />
      </div>
      {/* 搜索栏 */}
      <Form
        style={{
          width: "1000px",
          height: "40px",
          display: "flex",
          justifyContent: "left",
          backgroundColor: "white",
          margin: "5px",
        }}
        form={form}
      >
        <Form.Item name="khzt" style={{ width: "180px" }}>
          <Input
            placeholder="搜索关键字"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
          />
        </Form.Item>
        <Form.Item name="khxj" style={{ width: "180px", marginLeft: "10px" }}>
          <Select
            onChange={(e) => setCustomerStatus(e)}
            placeholder="商机阶段"
            options={[
              { value: "深入沟通", label: "深入沟通" },
              { value: "方案审核", label: "方案审核" },
              { value: "条款协商", label: "条款协商" },
              { value: "方案初定", label: "方案初定" },
              { value: "价格谈判", label: "价格谈判" },
              { value: "合作规划", label: "合作规划" },
              { value: "结果评估", label: "结果评估" },
              { value: "协议履行", label: "协议履行" },
              { value: "执行推进", label: "执行推进" },
              { value: "客户维护", label: "客户维护" },
            ]}
          />
        </Form.Item>
        <Form.Item
          name="name"
          style={{ width: "180px", margin: 0, padding: 0, marginLeft: "10px" }}
        >
          <Select
            placeholder="商机来源"
            onChange={(e) => setCustomerType(e)}
            options={[
              {
                value: "广州市新创智能科技有限公司",
                label: "广州市新创智能科技有限公司",
              },
              {
                value: "东莞市华科电子有限公司",
                label: "东莞市华科电子有限公司",
              },
              {
                value: "佛山市星辰软件科技有限公司",
                label: "佛山市星辰软件科技有限公司",
              },
              {
                value: "惠州市旭日科技有限公司",
                label: "惠州市旭日科技有限公司",
              },
              {
                value: "珠海市海韵信息技术有限公司",
                label: "珠海市海韵信息技术有限公司",
              },
              {
                value: "中山市宏业科技发展有限公司",
                label: "中山市宏业科技发展有限公司",
              },
              {
                value: "江门市创想科技有限公司",
                label: "江门市创想科技有限公司",
              },
              {
                value: "汕头市华宇科技有限公司",
                label: "汕头市华宇科技有限公司",
              },
              {
                value: "湛江市鑫达科技有限公司",
                label: "湛江市鑫达科技有限公司",
              },
              {
                value: "肇庆市联创科技有限公司",
                label: "肇庆市联创科技有限公司",
              },
            ]}
          />
        </Form.Item>
        <Form.Item
          name="name"
          style={{ width: "300px", marginLeft: "10px", display: "flex" }}
        >
          <Button
            style={{ marginLeft: "5px" }}
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
          >
            查询
          </Button>
          <Button
            style={{ marginLeft: "5px" }}
            icon={<RedoOutlined />}
            onClick={() => {
              form.resetFields();
              getDate();
            }}
          >
            重置
          </Button>
          <Button icon={<HourglassOutlined />} style={{ marginLeft: "5px" }}  onClick={showDrawer}>
            报价金额
          </Button>
        </Form.Item>
      </Form>
      {/* 按钮 */}
      <Button
        type="primary"
        icon={<PlusOutlined />}
        style={{ marginRight: "10px" }}
        onClick={() => {
          setTitle("添加");
          showModal();
          setObjItem({});
        }}
      >
        添加
      </Button>
      {/* 表格列表 */}
      <div>
        <Table<DataType>
          rowKey="id"
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
          onChange={onChange}
          pagination={{ defaultCurrent: 1, defaultPageSize: 6 }}
          showSorterTooltip={{ target: "sorter-icon" }}
        />
      </div>

      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Modals
          title={title}
          onCancel={handleCancel}
          onOk={handleOk}
          objItem={objItem}
          key={new Date().getTime()}
        />
      </Modal>
         {/* 抽屉 */}
         <>
            <Drawer title="查看报价数据" onClose={onClose} open={open}>
              <div
                style={{
                  marginLeft: "10px",
                  background: "rgba(255, 255, 255)",
                }}
              >
                {data.map((item) => {
                  return (
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        padding: "10px",
                      }}
                    >
                      <span>{item.name}</span>
                      <span>{item.phone}</span>
                    </div>
                  );
                })}
              </div>
            </Drawer>
          </>
    </div>
  );
}
